﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace HtmlReader
{
    public partial class Form1 : Form
    {
        string flagStart = "<TR valign=\"TOP\"><TD align=\"right\"><font size=2>";
        int flagStartLength = 48;
        string flagEnd = "&nbsp;";
        //string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"html\";    //文件目录
        string path = string.Empty;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "网页|*.html";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string fileName = openFileDialog.SafeFileName;
                    string name = fileName.Substring(0, fileName.LastIndexOf("."));

                    path = openFileDialog.FileName.Substring(0, openFileDialog.FileName.Length - fileName.Length);

                    WebClient MyWebClient = new WebClient();

                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据

                    Byte[] pageData = MyWebClient.DownloadData(openFileDialog.FileName); //从指定网站下载数据

                    string pageHtml = Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312，则使用这句            

                    //string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8，则使用这句

                    int first = pageHtml.IndexOf(flagStart);
                    int next = first;
                    int end;
                    bool flag = first >= 0;

                    if (!flag)
                    {
                        MessageBox.Show("该文件无法解析！");
                        return;
                    }

                    List<string> list = new List<string>();
                    StringBuilder sb = new StringBuilder();

                    while (flag)
                    {
                        end = pageHtml.IndexOf(flagEnd, next);

                        string id = pageHtml.Substring(next + flagStartLength, end - next - flagStartLength);
                        if (id.Length > 8)
                        {
                            id = id.Substring(id.Length - 8);
                        }
                        if (!list.Contains(id))
                        {
                            list.Add(id);
                            sb.Append(id);
                            sb.Append(",");
                        }

                        next = pageHtml.IndexOf(flagStart, next + 1);

                        flag = next >= 0;
                    }

                    //查找blank
                    int posBlank = pageHtml.IndexOf("BLANK");
                    int posX1 = pageHtml.IndexOf(" x ", posBlank);
                    int posX2 = pageHtml.IndexOf(" x ", posX1 + 3);
                    int posBlankEnd = pageHtml.IndexOf("<!--", posX2);
                    string blank = pageHtml.Substring(posX2 + 4, posBlankEnd - posX2 - 4);
                    blank = blank.Replace(Environment.NewLine, "").Trim();

                    sb.Append(blank);

                    if (!Directory.Exists(path))//若文件夹不存在则新建文件夹   
                    {
                        Directory.CreateDirectory(path); //新建文件夹   
                    }

                    QRCodeHandler qr = new QRCodeHandler();
                    string qrString = sb.ToString();                         //二维码字符串
                    string filePath = path + name + ".jpg";                                        //二维码文件名
                    qr.CreateQRCode(qrString, "Byte", 2, 0, "H", filePath, false, string.Empty);   //生成

                    //插入二维码
                    int posPic = pageHtml.IndexOf("</TABLE>") + 8;
                    pageHtml = pageHtml.Insert(posPic, "<div style='width:600px'><p style='text-align:right'><img src=\"" + name + ".jpg\"/></p></div>");

                    //插入打印按钮
                    int posButton = pageHtml.IndexOf("<BODY") + 37;
                    string strButton = @"<div style='width:600px'><p style='text-align:right'><input type='button' onclick='printWebPage(this);' value='Print' /></p></div>";
                    pageHtml = pageHtml.Insert(posButton, strButton);

                    //插入打印方法
                    int posPrint = pageHtml.IndexOf("</HEAD>");
                    string strPrint = @"<script>
                        function printWebPage(obj)
                        {  
                            obj.style.display='none';
                            window.print(); 
                            obj.style.display='';
                        } 
                        </script>";
                    pageHtml = pageHtml.Insert(posPrint, strPrint);

                    string extension = System.IO.Path.GetExtension(openFileDialog.FileName);
                    string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(openFileDialog.FileName);

                    using (StreamWriter sw = new StreamWriter(path + fileNameWithoutExtension + "_barcode" + extension))//将获取的内容写入文本
                    {
                        sw.Write(pageHtml);
                    }

                    //打开文件
                    System.Diagnostics.Process.Start(path + fileNameWithoutExtension + "_barcode" + extension);
                }

                catch (WebException webEx)
                {
                    Console.WriteLine(webEx.Message.ToString());
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            //Color c = Color.FromArgb(41, 125, 194);
            //e.Graphics.DrawString("文件存储路径：", new Font("微软雅黑", 10), new SolidBrush(Color.Black), 10, 270);
            //e.Graphics.DrawString(path, new Font("微软雅黑", 10), new SolidBrush(Color.Black), 10, 285);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(path))
            {
                MessageBox.Show("请先选择文件!");
            }
            else
            {
                System.Diagnostics.Process.Start("Explorer.exe", path);
            }
        }
    }
}
